/**
 * Copyright (C) 2014 Jonas Lammers
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */
package mygame;

import java.util.ArrayList;
import java.util.List;
import javax.vecmath.Vector3d;

/**
 *
 * @author jonas
 */
public class Broadphase {
    
    private ArrayList<CollisionResult> results;
    private Vector3d contactPoint;
    
    public Broadphase(){
        this.results = new ArrayList<CollisionResult>();
        this.contactPoint = new Vector3d();
    }
    
    public void checkCollisions(List<CollisionObject> list1, 
            List<CollisionObject> list2){
        check(list1,list2);
    }
    
    public void checkCollisions(List<CollisionObject> list){
        int size = list.size();
        List<CollisionObject> list1 = list.subList(0, size/2);
        List<CollisionObject> list2 = list.subList(size/2, size);
        check(list1,list2);
    }
    
    private void check(List<CollisionObject> list1, 
            List<CollisionObject> list2){
        results.clear();
        for(CollisionObject o1 : list1){
            for(CollisionObject o2 : list2){
                if(overlap(o1,o2)){
                    this.results.add(new CollisionResult(o1,o2,contactPoint));
                }
            }
        }
    }
    
    public List<CollisionResult> getCollisionResultList(){
        return this.results;
    }
    
    private boolean overlap(CollisionObject o1, CollisionObject o2){
        if(o1.equals(o2)) return false;
        double xd = o2.getPosition().getX() - o1.getPosition().getX();
	double yd = o2.getPosition().getY() - o1.getPosition().getY();
	double zd = o2.getPosition().getZ() - o1.getPosition().getZ();
        double dimeter = o1.getBoundingRadius() + o2.getBoundingRadius();
        double distance3 = xd*xd + yd*yd + zd*zd;
        if ( distance3 < dimeter*dimeter) return true;
        else return false;
    }
}
